<template>
	<!-- <div class="top">
		<el-breadcrumb separator="/">
			<el-breadcrumb-item :to="{ path: '/index' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>
				<a href="/Classification">课程管理</a>
			</el-breadcrumb-item>
			<el-breadcrumb-item>课程信息管理</el-breadcrumb-item>
		</el-breadcrumb>
	</div> -->
	<BreadCrumb pathOne="课程管理" pathTwo="课程信息管理"></BreadCrumb>
	<div class="middle">
		<el-form :inline="true" :model="queryInfo" class="demo-form-inline form-search" size="large">
			<el-form-item label="课程名称">
				<el-input v-model="queryInfo.title" placeholder="请输入课程名称" clearable @clear="queryInfo.title=''" />
			</el-form-item>
			<el-form-item label="课程分类">
				<el-select @clear="queryInfo.classifyId=''" clearable v-model="queryInfo.classifyId"
					placeholder="请选择课程分类" size="large" style="width: 200px">
					<el-option v-for="(item,index) in classifyAll" :value="item.id" :label="item.name" />
				</el-select>
			</el-form-item>
			<el-form-item label="心理师名">
				<el-input v-model="queryInfo.consultantName" placeholder="请输入心理师名" clearable
					@clear="queryInfo.consultantName=''" />
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="querydata">搜索</el-button>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="add">新增课程</el-button>
			</el-form-item>
			<el-form-item>
				<el-button type="danger" @click="remove">批量删除</el-button>
			</el-form-item>
		</el-form>
	</div>

	<div class="bottom">
		<el-table :data="tableData" row-key="id" style="width: 100%" @selection-change="handleSelectionChange" border
			class="course-table">
			<el-table-column type="selection" width="55" />
			<el-table-column prop="id" label="课程ID" width="80" align="center" />
			<el-table-column prop="title" label="课程名称" width="120" align="center" />
			<el-table-column label="缩略图">
				<template #default="scope">
					<el-avatar shape="square" size="large" :src="getOssImageUrl(scope.row.thumbnail)" />
				</template>
			</el-table-column>
			<!-- <el-table-column prop="duration" label="时长" width="100" align="center" /> -->
			<el-table-column label="视频总时长" width="100" align="center">
			  <template #default="scope">
			    <!-- 使用格式化方法转换时长 -->
			    {{ formatDuration(scope.row.duration) }}
			  </template>
			</el-table-column>
			<el-table-column prop="videoCount" label="数量" width="50" align="center" />
			<el-table-column prop="studyCount" label="学习量" width="100" align="center" />
			<el-table-column prop="description" label="简介" show-overflow-tooltip />
			<el-table-column prop="discountPrice" label="价格" width="100" align="center" />
			<el-table-column prop="courseClassify.name" label="分类" width="120" align="center" />
			<el-table-column prop="consultant.name" label="心理导师名" align="center" />
			<el-table-column label="操作" width="180" align="center">
				<template #default="scope">
					<el-button size="default" type="primary" @click="editdata(scope.row)">编辑</el-button>
					<el-button size="default" type="danger" @click="deletedata(scope.row.id)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<div class="demo-pagination-block">
			<el-pagination v-model:current-page="queryInfo.pageNum" v-model:page-size="queryInfo.pageSize"
				:page-sizes="[5, 10, 15, 20]" layout="total, sizes, prev, pager, next, jumper" :total="total"
				@size-change="handleSizeChange" @current-change="handleCurrentChange" />
		</div>
	</div>

	<el-dialog v-model="dialogFormVisible" :title="Title" @close="cancle" >
		<el-form :model="form" label-width="110px" class="dialog-form" size="large">
			<el-form-item label="课程名称">
				<el-input v-model="form.title" autocomplete="off" placeholder="请输入课程名称"/>
			</el-form-item>
			<!-- <el-form-item label="课程时长">
				<el-input v-model="form.duration" autocomplete="off" />
			</el-form-item>
			<el-form-item label="课程数量">
				<el-input v-model="form.videoCount" autocomplete="off" />
			</el-form-item> -->
			<el-form-item label="课程缩略图">
				<el-upload :action="getUploadUrl()" list-type="picture-card" :on-success="handleSuccess"
					:limit="1" :on-preview="handlePictureCardPreview" :file-list="fileList" :on-remove="handleRemove">
					<el-icon style="width: 128px; height: 128px;border: 1px dashed #DCDFE6; border-radius: 5px;font-size: 20px;">
						<Plus />
					</el-icon>
				</el-upload>
				<!-- 放大预览组件: 和官网一致 -->
				<el-dialog v-model="dialogVisibleImage">
					<img w-full :src="dialogImageUrl" alt="Preview Image" />
				</el-dialog>
			</el-form-item>
			<el-form-item label="适用人群">
				<el-input v-model="form.suitableFor" autocomplete="off" placeholder="请输入适用人群"/>
			</el-form-item>
			<el-form-item label="学习收获">
				<el-input v-model="form.learningGains" autocomplete="off" placeholder="请输入学习收获"/>
			</el-form-item>
			<el-form-item label="订阅须知">
				<el-input v-model="form.subscriptionNotes" autocomplete="off" placeholder="请输入订阅须知"/>
			</el-form-item>
			<el-form-item label="课程原价格">
				<el-input v-model="form.originalPrice" autocomplete="off" placeholder="请输入课程原价格"/>
			</el-form-item>
			<el-form-item label="课程现价格">
				<el-input v-model="form.discountPrice" autocomplete="off" placeholder="请输入课程现价格"/>
			</el-form-item>
			<!-- <el-form-item label="心理师名">
				<el-input v-model="form.consultantName" autocomplete="off" placeholder="请输入心理师名"/>
			</el-form-item> -->
			<el-form-item label="心理师名" >
				<el-select v-model="form.consultantId" placeholder="请选择心理导师" size="large">
					<el-option v-for="(item,index) in AllAuthor" :value="item.id" :label="item.name" />
				</el-select>
			</el-form-item>
			<el-form-item label="课程分类">
				<el-select @clear="form.classifyId=''" clearable v-model="form.classifyId"
					placeholder="请选择课程分类" size="large">
					<el-option v-for="(item,index) in classifyAll" :value="item.id" :label="item.name" />
				</el-select>
			</el-form-item>
			<el-form-item label="课程简介">
				<el-input v-model="form.description" autocomplete="off" type="textarea" placeholder="请输入课程简介"/>
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="cancle">取消</el-button>
				<el-button type="primary" @click="addform">确定</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script lang="ts" setup>
	import { getCurrentInstance, onMounted, reactive } from 'vue'
	import { ref } from 'vue'
	import { ElMessage, ElMessageBox, type TableInstance } from 'element-plus'
	import type { ComponentSize } from 'element-plus'
	import BreadCrumb from "../../components/BreadCrumb.vue"
	import { OSS_CONFIG, getOssImageUrl,getUploadUrl } from '../../util/ossConfig';
	
	// 时长格式化方法：将毫秒转换为 hh:mm:ss
	const formatDuration = (ms) => {
	  // 处理无效值
	  if (!ms || ms <= 0) return '00:00:00';
	  
	  // 转换毫秒为总秒数
	  const totalSeconds = Math.floor(ms / 1000);
	  
	  // 计算时、分、秒
	  const hours = Math.floor(totalSeconds / 3600);
	  const minutes = Math.floor((totalSeconds % 3600) / 60);
	  const seconds = totalSeconds % 60;
	  
	  // 补零操作，确保每位都是两位数
	  const pad = (num) => num.toString().padStart(2, '0');
	  
	  return `${pad(hours)}:${pad(minutes)}:${pad(seconds)}`;
	};
	const multipleTableRef = ref<TableInstance>()
	const queryInfo = reactive({
		id: 0,
		title: '',
		classifyId: '',
		consultantName: "",
		pageSize: 10,
		pageNum: 1
	});
	const tableData = ref([]);
	const total = ref(0);
	const Title = ref('')
	const axios = getCurrentInstance().appContext.config.globalProperties.axios;
	const querydata = () => {
		axios.get('course/page', {
			params: queryInfo
		}).then((resp) => {
			if (resp.code == 200) {
				console.log(resp);
				tableData.value = resp.data.list;
				total.value = resp.data.total;
			}
		})
	}
	const classifyAll = ref([])
	const getClassify = () => {
		axios.get('courseClassify').then((resp) => {
			if (resp.code == 200) {
				console.log(resp);
				classifyAll.value = resp.data;
			}
		})
	}
	const AllAuthor = ref([])
	const getAllAuthor = () => {
		axios.get(
			`consultantAllPsychology`,
		).then(resp => {
			console.log('全部作者：', resp);
			AllAuthor.value = resp.data
		})
	}
	onMounted(() => {
		querydata()
		getClassify()
		getAllAuthor()
	})

	const size = ref<ComponentSize>('default')
	const background = ref(false)
	const disabled = ref(false)

	const handleSizeChange = (val : number) => {
		queryInfo.pageSize = val;
		querydata()
	}
	const handleCurrentChange = (val : number) => {
		queryInfo.pageNum = val;
		querydata()
	}


	const dialogFormVisible = ref(false)

	const formLabelWidth = '140px'

	const form = ref({
		classifyId: '',
		consultantId:'',
		consultantName:"",
		description:"",
		discountPrice:'',
		duration:'',
		id:'',
		learningGains:"",
		originalPrice:'',
		studyCount:'',
		subscriptionNotes:"",
		suitableFor:"",
		thumbnail:'',
		title:"",
		videoCount:'',
	})
	const add = () => {
		Title.value = '新增课程',
		fileList.value = []
			dialogFormVisible.value = true
	}
	const cancle = () => {
		form.value = {
			classifyId: '',
			consultantId:'',
			consultantName:"",
			description:"",
			discountPrice:'',
			duration:'',
			id:'',
			learningGains:"",
			originalPrice:'',
			studyCount:'',
			subscriptionNotes:"",
			suitableFor:"",
			thumbnail:'',
			title:"",
			videoCount:'',
		}
		dialogFormVisible.value = false
		querydata()
	}
	const addform = () => {
		if (form.value.id) {
			// 编辑操作
			axios.put('course', form.value).then((resp) => {
				if (resp.code == 200) {
					dialogFormVisible.value = false;
					querydata();
					ElMessage.success('编辑成功');
				} else {
					ElMessage.error('编辑失败');
				}
			}).catch(error => {
				console.error('Error:', error);
				ElMessage.error('请求出错，请重试');
			})
		} else {
			// 新增操作
			axios.post('course', form.value).then((resp) => {
				if (resp.code == 200) {
					dialogFormVisible.value = false;
					querydata();
					ElMessage.success('新增成功');
				} else {
					ElMessage.error('新增失败');
				}
			}).catch(error => {
				console.error('Error:', error);
				ElMessage.error('请求出错，请重试');
			})
		}
	}
	const editdata = (row) => {
		console.log(row);
		Title.value = "编辑课程"
		dialogFormVisible.value = true;
		form.value = row
		if (row.thumbnail) {
			fileList.value = [{
				url: getOssImageUrl(row.thumbnail)
			}]
		} else {
			fileList.value = []
		}
	}

	const deletedata = (id) => {
		ElMessageBox.confirm(
			'确定要删除此课程吗？',
			'提示',
			{
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}
		).then(() => {
			axios.delete(`course/${id}`).then((resp) => {
				if (resp.code == 200) {
					querydata();
					ElMessage.success('删除成功');
				} else {
					ElMessage.error('删除失败');
				}
			}).catch(error => {
				console.error('Error:', error);
				ElMessage.error('请求出错，请重试');
			})
		}).catch(() => {
			// 用户取消操作
		})

	}

	const remove = () => {
		if (!multipleSelection.value) {
			ElMessage.info('请选择要删除的数据')
			return
		}
		ElMessageBox.confirm(
			'确定要删除此课程吗？',
			'提示',
			{
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}
		).then(() => {
			axios.delete(`course?ids=${multipleSelection.value}`).then((resp) => {
				if (resp.code == 200) {
					querydata();
					ElMessage.success('删除成功');
				} else {
					ElMessage.error('删除失败');
					console.log(multipleSelection.value);
				}
			}).catch(error => {
				console.error('Error:', error);
				ElMessage.error('请求出错，请重试');
			})
		}).catch(() => {
			// 用户取消操作
		})

	}
	const multipleSelection = ref('')
	const handleSelectionChange = (val) => {
		multipleSelection.value = val.map(item => item.id).join(',')
	}
	// 图片上传
	    const dialogImageUrl = ref('') // 图片预览框的地址
	    const dialogVisibleImage = ref(false) // 控制图片预览框是否显示
	    const fileList = ref([])
	    // 上传成功的回调，res服务器响应的数据
	    const handleSuccess = (res, file) => {
	        console.log("图片上传成功", res)
	
	        form.value.thumbnail = res.data; // res.data就是图片上传的地址
	    }
	    // 处理删除图片
	    const handleRemove = (file, fileList) => {
	        form.value.thumbnail = ''
	    }
	    // 处理图片预览
	    const handlePictureCardPreview = (file) => {
			console.log("file:",file)
	        dialogImageUrl.value = file.url;
	        dialogVisibleImage.value = true;
	    }
</script>

<style scoped>
	/* .top {
	margin-bottom: 20px;
} */
	/* .form-search {
	background: #fff;
	padding: 20px 24px 0 24px;
	border-radius: 8px;
	box-shadow: 0 2px 8px rgba(0,0,0,0.03);
} */
	/* .middle {
	margin-bottom: 20px;
} */
	/* .course-table {
	background: #fff;
	border-radius: 8px;
	box-shadow: 0 2px 8px rgba(0,0,0,0.03);
} */
	.demo-pagination-block {
		margin: 24px 0 0 0;
		text-align: right;
	}

	.dialog-form {
		padding-top: 10px;
	}

	/* .el-select {
	width: 150px;
} */
</style>